<template>
  <div>
    <div>
      <el-tree
        ref="tree"
        :props="{'label':'name'}"
        :data="treeData"
        show-checkbox
        default-expand-all
        check-strictly
        node-key="id"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList, assignPermissionAPI } from '@/api/permission'
import { getRolesByIdAPI } from '@/api/setting'
import { getTreeData } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treeData: [] // 树形结构数据
    }
  },
  created() {
    this.getPermissionList()
    this.getRolesById()
  },
  methods: {
    // 获取权限列表数据
    async getPermissionList() {
      const res = await getPermissionList()
      this.treeData = getTreeData(res.data, '0')
    },
    // 获取某一个角色数据
    async getRolesById() {
      const res = await getRolesByIdAPI(this.roleId)
      // 设置当前选择的节点
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      const res = this.$refs.tree.getCheckedKeys()
      await assignPermissionAPI({ id: this.roleId, permIds: res })
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
